package com.jeeplus.modules.common.excel.common.validator.impl.base;

import com.jeeplus.modules.common.excel.common.anno.base.IsDate;
import com.jeeplus.modules.common.excel.common.validator.abs.AbstractValidator;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 日期格式校验
 * @author wang.yishu
 */
public class IsDateValidator extends AbstractValidator {
    private IsDate isDate;
    @Override
    public boolean canValidate(Field field) {
        isDate = field.getDeclaredAnnotation(IsDate.class);
        return isDate != null;
    }

    @Override
    public String toValidate(Object entity, Field field) {
        if (entity == null) return isDate.msg();
        field.setAccessible(true);
        try {
            Object value = field.get(entity);
            if (value == null) return null;
            String pattern = isDate.pattern();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
            simpleDateFormat.setLenient(false);
            try {
                simpleDateFormat.parse(value.toString());
            } catch (ParseException e) {
                return isDate.msg();
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
